﻿/**
YASTACS nameextractor main entry point.

Authors: Kalman Kiss, kiskami@freemail.hu

Copyright:

Bugs:

Date: 

License: GNU General Public License

YASTACS game
Copyright (C) 2012 Kalman Kiss, kiskami@freemail.hu

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

Contact author at: kiskami@freemail.hu or
Hungary, 8900 Zalaegerszeg
Kakukkfu u 4.
*/
module main;

import std.stdio;
import std.getopt;
import std.path;
import std.file;
import std.regex;
import std.conv;

int main(string[] argv)
{
	debug writeln("nameextractor start");
	debug scope(exit) writeln ("nameextractor end");

	string inputfilename, outputfilename
		// href="/name/thor">THOR</a>
		, regexstr = `href="/name/([^"]+)"`;
	bool usestdin = false
		, darray = false;


	getopt(argv, "infile|i", &inputfilename
				, "outfile|o", &outputfilename
				, "regex|r", &regexstr
				, "darray|d", &darray);
	if(inputfilename is null) {
		debug writeln ("No infile given, using stdin.");
		inputfilename = "outputfile.html";
		usestdin = true;
	}
	if(outputfilename is null) {
		outputfilename = stripExtension(inputfilename) ~ ".d";
	}

	char[] buffer;
	if(!usestdin)
		buffer = cast(char[]) read(inputfilename);
	else {
		string buf;
		while ((buf = readln()) != null) 
			buffer ~= buf;
	}

	auto m = match(buffer, regex(regexstr, "g"));

	auto f = File(outputfilename, "w");
	if(darray) f.writeln("string[] ", baseName(stripExtension(outputfilename)), " = [ ");

	bool[string] cache;

	while(!m.empty) {
		string cap = replace(to!string(m.captures[1])
							 ,regex("[0-9-].", "g")
							 ,"x");
		m.popFront();
		if(cap in cache) {
			continue;
		}

		cache[cap] = true;
		if(darray) f.write(`"`);
		f.write(cap);
		if(darray) {
			if(!m.empty) f.writeln(`", `);
		} else {
			f.writeln();
		}
	}
	if(darray) f.writeln("\n ];");
		else f.writeln("\n");

	debug writeln("Wrote ", cache.length, " words.");

	return 0;
}
